﻿using System;
using System.IO;
using System.Text;

namespace CanAmFramework.CopyData
{
    public class ArgumentParser
    {
        #region Data Members
        string[] args;
        #endregion

        public ArgumentParser(string[] args)
        {
            this.args = args;
        }

        public string GetArgumentValue(string argumentName, bool required)
        {
            int argLoc = Array.IndexOf(args, "/" + argumentName);
            if (argLoc == -1 || args.Length <= argLoc + 1)
            {
                if (required)
                    throw new ArgumentException(string.Format("Required argument /{0} not provided.", argumentName));
                else
                    return null;
            }
            return args[argLoc + 1];
        }

        public bool GetFlag(string flagName)
        {
            int argLoc = Array.IndexOf(args, "/" + flagName);
            return (argLoc > -1);
        }

        /// <summary>
        /// Gets an argument, validating that it is a valid file location
        /// </summary>
        /// <param name="argumentName"></param>
        /// <param name="required"></param>
        /// <returns></returns>
        public string GetFileLocationArgument(string argumentName, bool required)
        {
            string value = GetArgumentValue(argumentName, required);
            if (!string.IsNullOrEmpty(value))
            {
                string dir;
                if (Path.HasExtension(value))
                    dir = Path.GetDirectoryName(value);
                else
                    dir = value;
                if (!Directory.Exists(dir))
                    throw new ArgumentException(string.Format("Argument /{0} refers to invalid directory: {1}", argumentName, dir));
            }
            return value;
        }
    }

}
